1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| package com.example.demo; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; @RestController public class LoadFontController {
@GetMapping("/test") public void test() throws IOException, FontFormatException { File file = new File("E://包图小白体.ttf"); Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, file);
Font font = dynamicFont.deriveFont(Font.PLAIN, 35); String srcImgPath = "E://15.jpg"; String tarImgPath = "E://" + System.currentTimeMillis() + ".jpg"; String waterMarkContent = "时光蹉跎,看淡岁月你我"; Color color = new Color(225, 225, 60); addWaterMark(srcImgPath, tarImgPath, waterMarkContent, color, font); } public void addWaterMark(String srcImgPath, String tarImgPath, Color markContentColor, String content, Font font) throws IOException { File srcImgFile = new File(srcImgPath); Image srcImg = ImageIO.read(srcImgFile); int srcImgWidth = srcImg.getWidth(null); int srcImgHeight = srcImg.getHeight(null); BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = bufImg.createGraphics(); g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null); g.setColor(markContentColor); g.setFont(font); int fontLen = getWatermarkLength(content, g); int line = fontLen / srcImgWidth; int y = (line + 1) * font.getSize(); System.out.println("水印文字总长度:" + fontLen + ",图片宽度:" + srcImgWidth + ",字符个数:" + content.length()); int tempX = 50; int tempY = y; int tempCharLen; int tempLineLen = 0; StringBuffer sb = new StringBuffer(); for (int i = 0; i < content.length(); i++) { char tempChar = content.charAt(i); tempCharLen = getCharLen(tempChar, g); tempLineLen += tempCharLen; if (tempLineLen >= srcImgWidth - 70) { g.drawString(sb.toString(), tempX, tempY); sb.delete(0, sb.length()); tempY += font.getSize(); tempLineLen = 0; } sb.append(tempChar); } g.drawString(sb.toString(), tempX, tempY); g.dispose(); FileOutputStream outImgStream = new FileOutputStream(tarImgPath); ImageIO.write(bufImg, "jpg", outImgStream); System.out.println("添加水印完成"); outImgStream.flush(); outImgStream.close(); }
public int getWatermarkLength(String waterMarkContent, Graphics2D g) { return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length()); }
public int getCharLen(char c, Graphics2D g) { return g.getFontMetrics(g.getFont()).charWidth(c); } }
|